package session01;

import java.sql.*;

public class TestDML {
    public static void main(String[] args) {
        //insert("G组", "中国", 4);
        //delete("G组");
        query();
    }

    //查询
    private static void query() {
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "123456";
        //1、创建Connection连接对象
        //2、通过Connection创建Statement语句对象
        try (Connection con = DriverManager.getConnection(url, user, password);
             Statement st = con.createStatement()) {
            //3、创建字符串的SQL语句
            String sql = "select f_groupName from t_group";
            //System.out.println(sql);
            //4、让statement语句对象执行sql
            ResultSet rs = st.executeQuery(sql);//返回值是一个集
            while (rs.next()) {
                String name = rs.getString("f_groupName");
                System.out.println(name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //删除
    private static void delete(String f_groupName) {
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "123456";

        try (Connection con = DriverManager.getConnection(url, user, password);
             Statement st = con.createStatement()) {
            String sql = "delete from t_group where f_groupName = '" + f_groupName + "'";
            //System.out.println(sql);
            st.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //添加
    public static void insert(String f_groupName, String f_groupAddress, int f_groupNum) {
        String url = "jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "123456";

        try (Connection con = DriverManager.getConnection(url, user, password);
             Statement st = con.createStatement()) {
            String sql = "insert into t_group(f_groupName,f_groupAddress,f_groupNum) values ('" + f_groupName + "','" + f_groupAddress + "'," + f_groupNum + ")";
            //System.out.println(sql);
            st.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
